package com.bmw.redis1.service.impl;

import com.bmw.redis1.base.BaseResponse;
import com.bmw.redis1.base.ClickRequest;
import com.bmw.redis1.base.Constant;
import com.bmw.redis1.dao.NewsDao;
import com.bmw.redis1.model.News;
import com.bmw.redis1.service.NewsService;
import com.bmw.redis1.util.DecrCacheStockUtil;
import com.bmw.redis1.util.ErrorMessage;
import com.bmw.redis1.util.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service("newsService")
@Slf4j
public class NewsServiceImpl implements NewsService {
    @Autowired
    NewsDao newsDao;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    DecrCacheStockUtil decrCacheStockUtil;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse renew(ClickRequest req) {
        log.info("===[开始调用访问量接口]===");
        Long messageId = req.getId();
        try {
            //校验文章信息。
            BaseResponse paramValidRes = validateParam(req.getId());
            if (paramValidRes.getCode() != 0){
                return paramValidRes;
            }
            log.info("===[校验][通过]===");


            if(hasOrderedUserCache(messageId)){
                log.error("===[文章已存在缓存中]===");
                decrCacheStockUtil.addStock(messageId);
                return BaseResponse.OK;
            }else {
                String key = String.format(Constant.redisKey.Message_VISITS,messageId);
                redisUtil.set(key,1);
                return BaseResponse.OK;
            }

        }catch (Exception e){
            log.error("异常");
            decrCacheStockUtil.decrStock(messageId);
            return BaseResponse.error(ErrorMessage.SYS_ERROR);
        }

    }

    private boolean hasOrderedUserCache(Long messageId) {
        String key = String.format(Constant.redisKey.Message_VISITS, messageId);
        return redisUtil.hasKey(key);
    }

    private BaseResponse validateParam(Long id) {
        News news = newsDao.selectByPrimaryKey(id);
        if (news == null) {
            log.error("===[文章不存在！]===");
            return BaseResponse.error(ErrorMessage.MESSAGE_NOT_EXIST);
        }
        return BaseResponse.OK;
    }
}
